package com.syt.order.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.commer.ResultCodeEnum;
import com.syt.commer.excption.YyghException;
import com.syt.common.utlis.HttpRequestHelper;
import com.syt.entity.enums.OrderStatusEnum;
import com.syt.entity.model.order.OrderInfo;
import com.syt.entity.model.user.Patient;
import com.syt.entity.vo.hosp.ScheduleOrderVo;
import com.syt.entity.vo.msm.MsmVo;
import com.syt.entity.vo.order.*;
import com.syt.hosp.client.HospitalFeignClient;
import com.syt.order.mapper.OrderMapper;
import com.syt.order.service.OrderService;
import com.syt.order.service.WeixinService;
import com.syt.rabbit.constant.MqConst;
import com.syt.rabbit.service.RabbitService;
import com.syt.user.client.PatientFeignClient;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired// 根据就诊人id获取就诊人信息
    private PatientFeignClient patientFeignClient;

    @Autowired// 根据排班id获取预约下单数据
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WeixinService weixinService;












//    65464541
//@Override
//@Transactional(rollbackFor = Exception.class)
//public Long saveOrder(String scheduleId, Long patientId) {
//    /**
//     * 1、需要通过远程调用     分步获取  就诊人信息 预约规则，排班信息
//     */
//    //获取就诊人信息
//    Patient patient = patientFeignClient.getPatientOrder(patientId);
//    //获取排班信息
//    ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
//
//    //判断当前时间不可以预约
//    if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
//            || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
//        throw new YyghException(ResultCodeEnum.TIME_NO);
//    }
//    //调用远程服务 获取签名
//    SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
//    System.out.println("signInfoVo" + signInfoVo.getApiUrl());
//    if(null == scheduleOrderVo) {
//        throw new YyghException(ResultCodeEnum.PARAM_ERROR);
//    }
//    if(scheduleOrderVo.getAvailableNumber() <= 0) {
//        throw new YyghException(ResultCodeEnum.NUMBER_NO);
//    }
//    //封装订单数据
//    OrderInfo orderInfo = new OrderInfo();
//    BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
//    String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
//    orderInfo.setOutTradeNo(outTradeNo);
//    orderInfo.setScheduleId(scheduleId);
//    orderInfo.setUserId(patient.getUserId());
//    orderInfo.setPatientId(patientId);
//    orderInfo.setPatientName(patient.getName());
//    orderInfo.setPatientPhone(patient.getPhone());
//    orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
//
//    this.save(orderInfo);
//
//    /**
//     *  2、利用HttpRequestHelper工具类 调用医院管理接口 获去或更新预约信息 如 已经预约人数，可预约人数
//     *  sendRequest()返回json数据
//     */
//    Map<String, Object> paramMap = new HashMap<>(23);
//    paramMap.put("hoscode",orderInfo.getHoscode());
//    paramMap.put("depcode",orderInfo.getDepcode());
//    // todo
//    paramMap.put("hosScheduleId","1");
//    paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
//    paramMap.put("reserveTime", orderInfo.getReserveTime());
//    paramMap.put("amount",orderInfo.getAmount());
//    paramMap.put("name", patient.getName());
//    paramMap.put("certificatesType",patient.getCertificatesType());
//    paramMap.put("certificatesNo", patient.getCertificatesNo());
//    paramMap.put("sex",patient.getSex());
//    paramMap.put("birthdate", patient.getBirthdate());
//    paramMap.put("phone",patient.getPhone());
//    paramMap.put("isMarry", patient.getIsMarry());
//    paramMap.put("provinceCode",patient.getProvinceCode());
//    paramMap.put("cityCode", patient.getCityCode());
//    paramMap.put("districtCode",patient.getDistrictCode());
//    paramMap.put("address",patient.getAddress());
//    //联系人
//    paramMap.put("contactsName",patient.getContactsName());
//    paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
//    paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
//    paramMap.put("contactsPhone",patient.getContactsPhone());
//    paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
//    String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
//    paramMap.put("sign", sign);
//
//    //调用下单方法
//    JSONObject result = HttpRequestHelper.sendRequest(paramMap,"http://localhost:9998/order/submitOrder");
//
//
//
//    //请求成功
//    if(result.getInteger("code") == 200) {
//        JSONObject jsonObject = result.getJSONObject("data");
//        //预约记录唯一标识（医院预约记录主键）
//        String hosRecordId = jsonObject.getString("hosRecordId");
//        //预约序号
//        Integer number = jsonObject.getInteger("number");;
//        //取号时间
//        String fetchTime = jsonObject.getString("fetchTime");;
//        //取号地址
//        String fetchAddress = jsonObject.getString("fetchAddress");;
//        //更新订单
//        orderInfo.setHosRecordId(hosRecordId);
//        orderInfo.setNumber(number);
//        orderInfo.setFetchTime(fetchTime);
//        orderInfo.setFetchAddress(fetchAddress);
//        baseMapper.updateById(orderInfo);
//        //排班可预约数
//        Integer reservedNumber = jsonObject.getInteger("reservedNumber");
//        //排班剩余预约数
//        Integer availableNumber = jsonObject.getInteger("availableNumber");
//
//        //3、发送mq信息更新号源和短信通知
//        //发送mq信息更新号源和短信通知
//        //发送mq信息更新号源
//        OrderMqVo orderMqVo = new OrderMqVo();
//        orderMqVo.setScheduleId(scheduleId);
//        orderMqVo.setReservedNumber(reservedNumber);
//        orderMqVo.setAvailableNumber(availableNumber);
//
//        //短信提示
//        MsmVo msmVo = new MsmVo();
//        msmVo.setPhone(orderInfo.getPatientPhone());
//        msmVo.setTemplateCode("SMS_220545305");
//        String reserveDate =
//                new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
//                        + (orderInfo.getReserveTime()==0 ? "上午": "下午");
//        Map<String,Object> param = new HashMap<String,Object>(){{
//            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
//            put("amount", orderInfo.getAmount());
//            put("reserveDate", reserveDate);
//            put("name", orderInfo.getPatientName());
//            put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
//        }};
//        msmVo.setParam(param);
//
//        orderMqVo.setMsmVo(msmVo);
//        //短信通知 实现不了
//        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
//
//
//    } else {
//        throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
//    }
//    return orderInfo.getId();//返回订单编号
//}


//    41654654





//    6321635
//生成挂号订单
//@Override
//public Long saveOrder(String scheduleId, Long patientId) {
//    //获取就诊人信息
//    Patient patient = patientFeignClient.getPatientOrder(patientId);
//
//    //获取排班相关信息
//    ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
//
//    //判断当前时间是否还可以预约
//    if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
//            || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
//        throw new YyghException(ResultCodeEnum.TIME_NO);
//    }
//
//    //获取签名信息
//    SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
//
//    //添加到订单表
//    OrderInfo orderInfo = new OrderInfo();
//    //scheduleOrderVo 数据复制到 orderInfo
//    BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
//    //向orderInfo设置其他数据
//    String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
//    orderInfo.setOutTradeNo(outTradeNo);
//    orderInfo.setScheduleId(scheduleId);
//    orderInfo.setUserId(patient.getUserId());
//    orderInfo.setPatientId(patientId);
//    orderInfo.setPatientName(patient.getName());
//    orderInfo.setPatientPhone(patient.getPhone());
//    orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
//    baseMapper.insert(orderInfo);
//
//    //调用医院接口，实现预约挂号操作
//    //设置调用医院接口需要参数，参数放到map集合
//    Map<String, Object> paramMap = new HashMap<>();
//    paramMap.put("hoscode",orderInfo.getHoscode());
//    paramMap.put("depcode",orderInfo.getDepcode());
//    paramMap.put("hosScheduleId",orderInfo.getScheduleId());
//    paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
//    paramMap.put("reserveTime", orderInfo.getReserveTime());
//    paramMap.put("amount",orderInfo.getAmount());
//
//    paramMap.put("name", patient.getName());
//    paramMap.put("certificatesType",patient.getCertificatesType());
//    paramMap.put("certificatesNo", patient.getCertificatesNo());
//    paramMap.put("sex",patient.getSex());
//    paramMap.put("birthdate", patient.getBirthdate());
//    paramMap.put("phone",patient.getPhone());
//    paramMap.put("isMarry", patient.getIsMarry());
//    paramMap.put("provinceCode",patient.getProvinceCode());
//    paramMap.put("cityCode", patient.getCityCode());
//    paramMap.put("districtCode",patient.getDistrictCode());
//    paramMap.put("address",patient.getAddress());
//    //联系人
//    paramMap.put("contactsName",patient.getContactsName());
//    paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
//    paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
//    paramMap.put("contactsPhone",patient.getContactsPhone());
//    paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
//
//    String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
//    paramMap.put("sign", sign);
//
//    //请求医院系统接口
//    JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
//
//    if(result.getInteger("code")==200) {
//        JSONObject jsonObject = result.getJSONObject("data");
//        //预约记录唯一标识（医院预约记录主键）
//        String hosRecordId = jsonObject.getString("hosRecordId");
//        //预约序号
//        Integer number = jsonObject.getInteger("number");;
//        //取号时间
//        String fetchTime = jsonObject.getString("fetchTime");;
//        //取号地址
//        String fetchAddress = jsonObject.getString("fetchAddress");;
//        //更新订单
//        orderInfo.setHosRecordId(hosRecordId);
//        orderInfo.setNumber(number);
//        orderInfo.setFetchTime(fetchTime);
//        orderInfo.setFetchAddress(fetchAddress);
//        baseMapper.updateById(orderInfo);
//        //排班可预约数
//        Integer reservedNumber = jsonObject.getInteger("reservedNumber");
//        //排班剩余预约数
//        Integer availableNumber = jsonObject.getInteger("availableNumber");
//        //发送mq消息，号源更新和短信通知
//        //发送mq信息更新号源
//        OrderMqVo orderMqVo = new OrderMqVo();
//        orderMqVo.setScheduleId(scheduleId);
//        orderMqVo.setReservedNumber(reservedNumber);
//        orderMqVo.setAvailableNumber(availableNumber);
//        //短信提示
//        MsmVo msmVo = new MsmVo();
//        msmVo.setPhone(orderInfo.getPatientPhone());
//        String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
//        Map<String,Object> param = new HashMap<String,Object>(){{
//            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
//            put("amount", orderInfo.getAmount());
//            put("reserveDate", reserveDate);
//            put("name", orderInfo.getPatientName());
//            put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
//        }};
//        msmVo.setParam(param);
//        orderMqVo.setMsmVo(msmVo);
//
//        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
//    } else {
//        throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
//    }
//    return orderInfo.getId();
//}
//    65+416













//    //生成挂号订单
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);

        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);

        //判断当前时间是否还可以预约
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        //获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        //添加到订单表
        OrderInfo orderInfo = new OrderInfo();
        //scheduleOrderVo 数据复制到 orderInfo
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
        //向orderInfo设置其他数据
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        baseMapper.insert(orderInfo);

        //调用医院接口，实现预约挂号操作
        //设置调用医院接口需要参数，参数放到map集合
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        //paramMap.put("hosScheduleId",1);
//        ++++++++++++++++++++++++++++++++++++++++++++
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);

        //调用医院管理接口 hospital-manager 实现下单
        Map<String, Object> map = this.setOrderMap(orderInfo, patient, signInfoVo);
        //请求医院系统接口
        //JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        //注意把hospital_set表中对应记录的url设置为
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");

//        JSONObject result = HttpRequestHelper.sendRequest(map, signInfoVo.getApiUrl() + "/order/submitOrder");
        System.out.println("321321321321:"+signInfoVo.getApiUrl());
        if(result.getInteger("code")==200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);

            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            //发送mq消息，号源更新和短信通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                put("code", "123456");
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);

            // 发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }


//    65464654
//封装下订单所用的参数
private Map<String, Object> setOrderMap(OrderInfo orderInfo, Patient patient, SignInfoVo signInfoVo){
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("hoscode",orderInfo.getHoscode());
    paramMap.put("depcode",orderInfo.getDepcode());
    //由于manager为mysql，order为mongo，故手动设置与mongo中对应的hosScheduleId
//        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
    paramMap.put("hosScheduleId", 2);
    paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
    paramMap.put("reserveTime", orderInfo.getReserveTime());
    paramMap.put("amount",orderInfo.getAmount());
    paramMap.put("name", patient.getName());
    paramMap.put("certificatesType",patient.getCertificatesType());
    paramMap.put("certificatesNo", patient.getCertificatesNo());
    paramMap.put("sex",patient.getSex());
    paramMap.put("birthdate", patient.getBirthdate());
    paramMap.put("phone",patient.getPhone());
    paramMap.put("isMarry", patient.getIsMarry());
    paramMap.put("provinceCode",patient.getProvinceCode());
    paramMap.put("cityCode", patient.getCityCode());
    paramMap.put("districtCode",patient.getDistrictCode());
    paramMap.put("address",patient.getAddress());
    paramMap.put("contactsName",patient.getContactsName());
    paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
    paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
    paramMap.put("contactsPhone",patient.getContactsPhone());
    paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
    String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
    paramMap.put("sign", sign);
    return paramMap;
}

//    6465465

    //根据订单id查询订单详情
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        System.out.println("0.20.201"+orderInfo);
        return this.packOrderInfo(orderInfo);
    }

    //订单列表（条件查询带分页）
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();// 开始时间
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();//结束时间

        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    //取消预约
    @Override
    public Boolean cancelOrder(Long orderId) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //判断是否取消
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if(quitTime.isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //调用医院接口实现预约取消
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);

        JSONObject result = HttpRequestHelper.sendRequest(reqMap,
                signInfoVo.getApiUrl()+"/order/updateCancelStatus");
        System.out.println("0000000000000:"+signInfoVo.getApiUrl());
        //根据医院接口返回数据
        if(result.getInteger("code")!=200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //判断当前订单是否可以取消
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                Boolean isRefund = weixinService.refund(orderId);
                if(!isRefund) {
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                //更新订单状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);

                //发送mq更新预约数量
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                //短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            }
        }
        return true;
    }

    //就诊通知
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        wrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);
        for(OrderInfo orderInfo:orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    //预约统计
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        //调用mapper方法得到数据
        List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCount(orderCountQueryVo);

        //获取x需要数据 ，日期数据  list集合
        List<String> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());

        //获取y需要数据，具体数量  list集合
        List<Integer> countList =orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        Map<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }
// 状态码
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

}
